<?php

namespace app\admins\controller;

class Home extends Base
{
    // 后台首页
    public function index()
    {
        // 后台菜单
        $menus = $this->admin_menu->where([
            ['ishidden', '=', 0],
            ['status', '=', 0],
            ['id', 'in', $this->auth['rights']]
        ])->order([
            'ord' => 'desc',
            'id' => 'asc',
        ])->select();
        // 无限级递归
        $menus = $this->levels($menus);
        // 无限极菜单
        $menus = $this->menus($menus);
        $this->app->view->assign('menus', $menus);
        $this->app->view->assign('auth', $this->auth);
        return $this->app->view->fetch();
    }

    // 后台欢迎页面
    public function welcome()
    {
        return $this->app->view->fetch();
    }

    // 无限级菜单
    private function menus($datas)
    {
        $res = '';
        foreach ($datas as $k => $data) {
            $res .= $this->childMenus($data, $k);
        }
        return $res;
    }

    // 递归子数据
    private function childMenus($data, $k = 0, $indent = 0)
    {
        $res = '';
        if ($data['children']) {
            $res .= sprintf('<li class="layui-nav-item%s">', $k === 0 ? ' layui-nav-itemed' : '');
            $res .= sprintf('<a href="javascript:;" style="text-indent:%dem;" title="%s">%s%s</a>', max($indent - 1, 0), strip_tags($data['title']), $data['icon'] ? '<i class="layui-icon ' . $data['icon'] . '"></i> ' : '', $data['title']);
            $res .= '<dl class="layui-nav-child">';
            foreach ($data['children'] as $k => $data) {
                if ($data['children']) {
                    $res .= $this->childMenus($data, $k, $indent + 1);
                } else {
                    $res .= sprintf('<dd><a href="javascript:;" style="text-indent:%dem;" data-controller="%s" data-action="%s" onclick="fireMenu(this)" title="%s">%s%s</a></dd>', $indent + 1, $data['controller'], $data['action'], strip_tags($data['title']), $data['icon'] ? '<i class="layui-icon ' . $data['icon'] . '"></i> ' : '', $data['title']);
                }
            }
            $res .= '</dl>';
            $res .= "</li>\n";
        } else {
            $res .= sprintf('<li class="layui-nav-item%s"><a href="javascript:;" data-controller="%s" data-action="%s" onclick="fireMenu(this)" title="%s">%s%s</a></li>', $k === 0 ? ' layui-this' : '', $data['controller'], $data['action'], strip_tags($data['title']), $data['icon'] ? '<i class="layui-icon ' . $data['icon'] . '"></i> ' : '', $data['title']);
        }
        return $res;
    }
}
